package com.core.plugin.quartz;

import java.util.Map.Entry;

import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;

import com.core.plugin.quartz.job.JobManager;
import com.jfinal.plugin.IPlugin;

public class QuartzPlugin implements IPlugin {
	
	private Scheduler scheduler;

	@Override
	public boolean start() {
		try {
			scheduler = StdSchedulerFactory.getDefaultScheduler();
			JobManager manager = new JobManager();
			for (Entry<JobDetail, Trigger> job : manager.getJobs().entrySet()) {
				scheduler.scheduleJob(job.getKey(), job.getValue());
			}
			scheduler.start();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		return true;
	}

	@Override
	public boolean stop() {
		try {
			if (scheduler != null) {
				for (JobExecutionContext job : scheduler.getCurrentlyExecutingJobs()) {
					scheduler.interrupt(job.getJobDetail().getKey());
				}
				scheduler.clear();
				scheduler.shutdown();
			}
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		return true;
	}
	
}
